import axios from 'axios'
import store from '@/store'

export function request (config) {
  // 1.创建axios的实例
  const instance = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 5000
  })
  // 正在进行中的请求列表
  const reqList = []

  // 阻止重复请求
  const stopRepeatRequest = function (reqList, url, cancel, errorMessage) {
    const errorMsg = errorMessage || ''
    for (let i = 0; i < reqList.length; i++) {
      if (reqList[i] === url) {
        cancel(errorMsg)
        return
      }
    }
    reqList.push(url)
  }

  const allowRequest = function (reqList, url) {
    for (let i = 0; i < reqList.length; i++) {
      if (reqList[i] === url) {
        reqList.splice(i, 1)
        break
      }
    }
  }
  // 2.axios的拦截器
  // 2.1.请求拦截的作用
  instance.interceptors.request.use(
    config => {
      // config：本次请求的请求配置对象
      const { userInfo, token } = store.state
      if (userInfo && token) {
        config.headers.Authorization = `Bearer ${token}`
      }

      let cancel
      // 设置cancelToken对象
      config.cancelToken = new axios.CancelToken(function (c) {
        cancel = c
      })
      // 阻止重复请求。当上个请求未完成时，相同的请求不会进行
      stopRepeatRequest(reqList, config.url, cancel, `${config.url} 请求被中断`)
      return config
    },
    err => {
      console.log(err)
    }
  )

  // 2.2.响应拦截
  instance.interceptors.response.use(
    res => {
      setTimeout(() => {
        allowRequest(reqList, res.config.url)
      }, 1000)
      return res.data
    },
    err => {
      if (axios.isCancel(err)) {
        console.log(err.message)
      } else {
        // 增加延迟，相同请求不得在短时间内重复发送
        setTimeout(() => {
          allowRequest(reqList, err.config.url)
        }, 1000)
      }

      console.log(err)
    }
  )

  // 3.发送真正的网络请求
  return instance(config)
}
